package library;

import java.sql.SQLException;
import java.util.HashMap;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.logger.LocalLog;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DaoUtil {
	final static String databaseName = "library_system_db.db";
	final static String databaseUrl = "jdbc:sqlite:" + databaseName;
	
	private static HashMap<Class, Dao> daoList = new HashMap<Class, Dao>();
	private static ConnectionSource connectionSource;
	
	public static void init() throws SQLException {
        System.setProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY, "ERROR");
		ConnectionSource conn = getConnectionSource();
		daoList.put(Librarian.class, DaoManager.createDao(conn, Librarian.class));
		daoList.put(Reader.class, DaoManager.createDao(conn, Reader.class));
		daoList.put(Book.class, DaoManager.createDao(conn, Book.class));
		daoList.put(BookingRecord.class, DaoManager.createDao(conn, BookingRecord.class));
		daoList.put(LibraryBranch.class, DaoManager.createDao(conn, LibraryBranch.class));
		checkTable();
	}
	
	@SuppressWarnings("unchecked")
	private static void checkTable() throws SQLException{
		for(Class key:daoList.keySet()){
			TableUtils.createTableIfNotExists(getConnectionSource(), key);
		}

	}
	
	public static ConnectionSource getConnectionSource() throws SQLException{
		if(connectionSource == null)
			connectionSource = new JdbcConnectionSource(DaoUtil.databaseUrl);
		return connectionSource;
	}
	
	public static <clazz> Dao<clazz, String> getDao(Class clazz) throws SQLException{
		Dao <clazz, String> dao = daoList.get(clazz);
		if(dao == null)
			throw new SQLException("Dao " + clazz.toString() + " Not found!");
		return dao;
	}
}
